//验证器
const loginValidate = require( '../../validator/loginValidater' )
//模型
const userModel = require( '../../db/models/userModel' );
const md5 = require( 'md5' );
//登录控制器
module.exports = {
    login ( req, res ) { 
        // console.log( 3 );
        //登录界面友好性处理
        //只要登陆过到登录页面直接跳转首页，没登陆过去登录
        if ( req.session[ 'username' ] ) {
            res.redirect( '/admin/index' );
        } else { 
            res.render( 'admin/login/index' );
        }
        // res.render('admin/login/index')
    },
    async dologin ( req, res ) { 
        //接受post表单数据
        let { username, password } = req.body;
        let { flag, msg } = loginValidate( username, password );
        if ( !flag ) {
            res.redirect( '/admin/login' );
        } else { 
            //表单验证通过
            // password = md5( password );
            if ( await userModel.checkLogin( username, password ) ) {
                req.session[ 'username' ] = username;
                // console.log(1);
                res.redirect( '/admin/index' );
            } else { 
                // console.log(2);
                res.status(403).redirect('/admin/login')
            }
        }
    }
}